package com.hex.ds.hdrs.agent.dao;

import com.alibaba.fastjson.JSONArray;
import com.hex.ds.hdrs.agent.po.AgentConf;
import com.hex.ds.hdrs.agent.vo.ResponseInf;
import com.hex.ds.hdrs.center.vo.MasterInitReq;
import com.hex.ds.hdrs.common.constant.HttpConst;
import com.hex.ds.hdrs.common.exception.BizException;
import com.hex.ds.hdrs.common.utils.HttpUtils;
import com.hex.ds.hdrs.log.service.LogService;
import com.hex.ds.hdrs.period.task.dto.TaskInfo;
import com.hex.ds.hdrs.period.task.vo.CycleTaskReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * agent接口类
 */
@Slf4j
@Component
public class AgentDao {

    @Autowired
    private LogService logService;

    /**
     * 发送到节点
     */
    public boolean sendPeriodTask(TaskInfo taskInfo, AgentConf agentConf) {
        try {
            String url = "http://" + agentConf.getAgentIp() + ":" + agentConf.getAgentPort() + "/cycleTask/runTask";
            CycleTaskReq req = new CycleTaskReq(taskInfo);
            log.debug("发送周期任务【sendPeriodTask】url:{}===\ncycleTaskReq:{}", url, req);
            String back = HttpUtils.httpJsonPost(url, req);
            ResponseInf rsp = JSONArray.parseObject(back, ResponseInf.class);
            // 添加通信日志
            logService.centerToAgent(taskInfo, url, rsp);
            if (rsp == null) {
                log.error("【sendPeriodTask】rsp为空");
                return false;
            } else if (HttpConst.HTTP_STATUS_OK.equals(rsp.getCode())) {
                return true;
            } else {
                log.error("【sendPeriodTask】发送异常，rsp:{}", rsp);
                return false;
            }
        } catch (BizException e) {
            log.error("【taskCode:{}】【bizDate:{}】【sendPeriodTask】异常:{}",
                    taskInfo.getTaskCode(), taskInfo.getBizDate(), e.getErrMsg(), e);
            throw e;
        }
    }

    /**
     * 定时任务发送到节点
     */
    public boolean sendCronTask(TaskInfo taskInfo, AgentConf agentConf) {
        try {
            String url = "http://" + agentConf.getAgentIp() + ":" + agentConf.getAgentPort() + "/cronTask/runTimeTask";
            log.debug("发送定时任务【sendCronTask】url:{}===\ntaskInfo:{}", url, taskInfo);
            String back = HttpUtils.httpJsonPost(url, taskInfo);
            ResponseInf rsp = JSONArray.parseObject(back, ResponseInf.class);
            // 添加通信日志
            logService.centerToAgent(taskInfo, url, rsp);
            if (rsp == null) {
                log.error("【sendCronTask】rsp为空");
                return false;
            } else if (HttpConst.HTTP_STATUS_OK.equals(rsp.getCode())) {
                return true;
            } else {
                log.error("【sendCronTask】发送异常，rsp:{}", rsp);
                return false;
            }
        } catch (BizException e) {
            log.error("【taskCode:{}】【bizDate:{}】【sendCronTask】异常:{}",
                    taskInfo.getTaskCode(), taskInfo.getBizDate(), e.getErrMsg(), e);
            throw e;
        }
    }

    /**
     * agent删除任务
     */
    public boolean delAgentTask(TaskInfo taskInfo, AgentConf agentConf) {
        try {
            String url = "http://" + agentConf.getAgentIp() + ":" + agentConf.getAgentPort() + "/cycleTask/delTask";
            log.info("删除agent任务【delAgentTask】url:{} ===\ntaskInfo:{}", url, taskInfo);
            String back = HttpUtils.httpJsonPost(url, taskInfo);
            ResponseInf rsp = JSONArray.parseObject(back, ResponseInf.class);
            // 添加通信日志
            logService.centerToAgent(taskInfo, url, rsp);
            if (rsp == null) {
                log.error("【delAgentTask】rsp为空");
                return false;
            } else if (HttpConst.HTTP_STATUS_OK.equals(rsp.getCode())) {
                return true;
            } else {
                log.error("【delAgentTask】发送异常，rsp:{}", rsp);
                return false;
            }
        } catch (BizException e) {
            log.error("【taskCode:{}】【bizDate:{}】【delAgentTask】异常:{}",
                    taskInfo.getTaskCode(), taskInfo.getBizDate(), e.getErrMsg(), e);
            throw e;
        }
    }

    /**
     * 查看agent的running中任务
     */
    public String qryAgentRunning(TaskInfo taskInfo, AgentConf agentConf) {
        try {
            String url = "http://" + agentConf.getAgentIp() + ":" + agentConf.getAgentPort() + "/cycleTask/qryRunning";
            log.info("查看agent的running中任务【qryAgentRunning】url:{}===\ntaskInfo:{}", url, taskInfo);
            String back = HttpUtils.httpJsonPost(url, taskInfo);
            ResponseInf rsp = JSONArray.parseObject(back, ResponseInf.class);
            // 添加通信日志
            logService.centerToAgent(taskInfo, url, rsp);
            if (rsp == null) {
                return "";
            } else if (HttpConst.HTTP_STATUS_OK.equals(rsp.getCode())) {
                return rsp.getMsg();
            } else {
                return "";
            }
        } catch (BizException e) {
            log.error("【taskCode:{}】【bizDate:{}】【sendPeriodTask】异常:{}",
                    taskInfo.getTaskCode(), taskInfo.getBizDate(), e.getErrMsg(), e);
            return "";
        }
    }

    /**
     * 测试连接agent
     *
     * @return
     */
    public boolean testLink(AgentConf agentConf) {
        String url = "http://" + agentConf.getAgentIp() + ":" + agentConf.getAgentPort() + "/agent/vaildConnect";
        log.info("测试连接【testLink】url: {}", url);
        try {
            String back = HttpUtils.httpGet(url, null);
            ResponseInf rsp = JSONArray.parseObject(back, ResponseInf.class);
            // 添加通信日志
            logService.centerToAgent(null, url, rsp);
            return true;
        } catch (Exception e) {
            log.error("连接失败，失败原因：{}", e.getMessage(), e);
            logService.centerToAgent(null, url, null);
            return false;
        }
    }

    /**
     * matser初始化完成
     *
     * @param agentConf
     * @param centerIp
     * @return
     */
    public boolean masterInitSucc(AgentConf agentConf, String centerIp) {
        try {
            String url = "http://" + agentConf.getAgentIp() + ":" + agentConf.getAgentPort() + "/agent/centerSwitch";
            MasterInitReq req = new MasterInitReq(centerIp);
            log.info("matser初始化完成【masterInitSucc】url:{}===\nmasterInitReq:{}", url, req);
            String back = HttpUtils.httpJsonPost(url, req);
            ResponseInf rsp = JSONArray.parseObject(back, ResponseInf.class);
            // 添加通信日志
            logService.centerToAgent(req, url, rsp);
            if (rsp == null) {
                log.error("【masterInitSucc】rsp为空");
                return false;
            } else if (HttpConst.HTTP_STATUS_OK.equals(rsp.getCode())) {
                return true;
            } else {
                log.error("【masterInitSucc】发送异常，rsp:{}", rsp);
                return false;
            }
        } catch (BizException e) {
            log.error("【agentName:{}】【masterInitSucc】异常:{}",
                    agentConf.getAgentName(), e.getErrMsg(), e);
            throw e;
        }
    }

    /**
     * kill 任务
     *
     * @param agentConf
     * @param taskInfo
     * @return
     */
    public boolean killTask(AgentConf agentConf, TaskInfo taskInfo) {
        try {
            String url = "http://" + agentConf.getAgentIp() + ":" + agentConf.getAgentPort() + "/cycleTask/killTaskProcess";
            CycleTaskReq req = new CycleTaskReq(taskInfo);
            log.info("kill任务【killTask】url:{}===\ncycleTaskReq:{}", url, req);
            String back = HttpUtils.httpJsonPost(url, req);
            ResponseInf rsp = JSONArray.parseObject(back, ResponseInf.class);
            if (rsp == null) {
                log.error("【killTask】rsp为空");
                return false;
            } else if (HttpConst.HTTP_STATUS_OK.equals(rsp.getCode())) {
                return true;
            } else {
                log.error("【killTask】发送异常，rsp:{}", rsp);
                return false;
            }
        } catch (BizException e) {
            log.error("【taskCode:{}】【bizDate:{}】【killTask】异常:{}",
                    taskInfo.getTaskCode(), taskInfo.getBizDate(), e.getErrMsg(), e);
            throw e;
        }
    }
}
